﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DAL3
{
    public class BartenderHelper
    {
        #region  BarTender打印方法
        private static BarTender.Application btApp = new BarTender.Application();
        private static BarTender.Format btFormat = new BarTender.Format();
        public string TemplateFile { set; get; }
        public string ErrorMsg { set; get; }
        public bool Status { set; get; }
        /// <summary>
        /// 使用 BarTender进行打印，批量打印
        /// </summary>
        /// <param name="labelName"> BarTender标签名称</param>
        /// <param name="labelParamsValues">打印数据</param>
        /// <param name="msg">消息</param>
        /// <param name="printQty">打印数量</param>
        /// <returns>打印OK true</returns>
        public bool BTPrint(string labelName, Dictionary<string, string> labelParamsValues, out string msg, int printQty = 1, string printer = "")
        {
            try
            {
                bool checkLabelVar = true;
                string tmpMsg = "";
                this.TemplateFile = labelName;

                if (!File.Exists(TemplateFile))
                {
                    msg = "Error:Label File Not Exists" + TemplateFile;
                    this.ErrorMsg = msg;
                    return false;
                }
                if (!string.IsNullOrEmpty(printer))
                {
                    bool printerFlag = false;
                    foreach (string sPrint in System.Drawing.Printing.PrinterSettings.InstalledPrinters)//获取所有打印机名称
                    {
                        if (sPrint.Equals(printer))
                        {
                            printerFlag = true; 
                        }
                    }

                    if (!printerFlag)
                    {
                        msg = "Error:Printer Name Error";
                        return false;
                    }

             
                }
                //找到打印模板的标签页
                btFormat = btApp.Formats.Open(labelName, false, "");
                if (!string.IsNullOrEmpty(printer))
                {
                    btFormat.Printer = printer;
                }
                if (btApp != null)
                {
                 

                    //取模板所有的值
                    string strBT = btFormat.NamedSubStrings.GetAll("#", "$");

                    //将模板所有值进行拆分
                    strBT = strBT.Substring(0, strBT.Length - 1);
                    string[] strBTValue = strBT.Split(new char[] { '$' });

                    //循环将模板的值写入lbldicVar中
                    Dictionary<string, string> lbldicVar = new Dictionary<string, string>();
                    for (int i = 0; i < strBTValue.Length; i++)
                    {
                        string[] cc = strBTValue[i].Split(new char[] { '#' });

                        lbldicVar.Add(cc[0].ToString(), cc[1].ToString()); //0是模板的参数 1是参数值
                    }
                    if (labelParamsValues.Count > 0)
                    {
                        foreach (var item in lbldicVar)
                        {
                            if (labelParamsValues.Count(q => q.Key.ToUpper() == item.Key.ToUpper()) == 0)
                            {
                                tmpMsg = "数据源缺少参数:  " + item.Key;
                                if (checkLabelVar)
                                {
                                    this.ErrorMsg = tmpMsg;
                                    checkLabelVar = false;
                                }
                                else
                                {
                                    this.ErrorMsg = this.ErrorMsg + (char)10 + tmpMsg;
                                }
                            }
                        }
                        if (!checkLabelVar)
                        {
                            msg = this.ErrorMsg;
                            this.Status = false;
                            return false;
                        }
                        foreach (var param in labelParamsValues.Keys)
                        {
                            if (lbldicVar.Keys.Count(q => q.ToUpper() == param.ToUpper()) > 0)
                            {
                                var labvar = lbldicVar.Keys.First(q => q.ToUpper() == param.ToUpper());

                                if (string.IsNullOrEmpty(labelParamsValues[param]))
                                {
                                    tmpMsg = "数据源参数值为空:" + labvar;
                                    if (checkLabelVar)
                                    {
                                        this.ErrorMsg = tmpMsg;
                                        checkLabelVar = false;
                                    }
                                    else
                                    {
                                        this.ErrorMsg = this.ErrorMsg + (char)10 + tmpMsg;
                                    }
                                }
                                btFormat.SetNamedSubStringValue(param, labelParamsValues[param]);
                            }
                        }
                        if (!checkLabelVar)
                        {
                            msg = this.ErrorMsg;
                            this.Status = false;
                            return false;
                        }
                        btFormat.IdenticalCopiesOfLabel =printQty;

                        //第二个false设置打印时是否跳出打印属性
                        btFormat.PrintOut(true, false);
                        //退出是是否保存标签
                        btFormat.Close(BarTender.BtSaveOptions.btSaveChanges);
                        //lblDoc.FormFeed();
                        msg = "OK";
                        this.ErrorMsg = msg;
                        this.Status = true;
                        return true;
                    }
                    else
                    {
                        msg = "Print Data is null";
                        this.ErrorMsg = msg;
                        this.Status = false;
                        return false;
                    }
                }
                else
                {
                    msg = "Error:CodeSoft Application can't boot up";
                    this.ErrorMsg = msg;
                    this.Status = false;
                    return false;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.InnerException;
                this.ErrorMsg = msg;
                this.Status = false;
                return false;
            }
            finally
            {
                if (btApp != null)
                {
                    btApp.Quit(BarTender.BtSaveOptions.btSaveChanges);//界面退出时同步退出bartender进程
                    //lblApp.Documents.CloseAll(true);
                    //lblDoc = null;
                }
                GC.Collect();
            }
        }
        #endregion

        #region 数据库调用打印
        /// <summary>
        /// 打印从文本数据库中打
        /// </summary>
        /// <returns></returns>
        public bool BTPrintByDataBase(string path,string filePath,string printer="") {

            try
            {
                BarTender.Application btapp;
                BarTender.Format btformat;
                btapp = new BarTender.Application();
                btformat = btapp.Formats.Open(path, false, "");
                BarTender.Database database = btformat.Databases.GetDatabase(1);
                if (!string.IsNullOrEmpty(printer)) {
                    btformat.Printer = printer;
                }
              
                database.TextFile.FileName = filePath;

                //database.SQLStatement += $" where printID='{printId}' order by RIGHT(Var1,7)";//填写SQL语句附加条件
                //database.Password = VSLoginInfo.SQLPassword;
                //database.User = VSLoginInfo.SQLUser;
                btformat.PrintOut(false, false); //第二个参数设置是否跳出打印属性;
                btapp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);//退出时同步退出bartender进程（SQL条件会改变，不更新模板信息）
                //     
            }
            catch {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 打印从文本数据库中打
        /// </summary>
        /// <param name="templatepath">模板地址</param>
        /// <param name="dataLine">数据行，一行一个标签，第一行为标题，多列逗号分割</param>
        /// <returns></returns>
        public bool BTPrintByDataBase(string templatepath, List<string> dataLine, string printer = "")
        {

            try
            {
                BarTender.Application btapp;
                BarTender.Format btformat;
                btapp = new BarTender.Application();
                var filepath = WriteLog(dataLine, "", Guid.NewGuid().ToString());
                btformat = btapp.Formats.Open(templatepath, false, "");
                BarTender.Database database = btformat.Databases.GetDatabase(1);
                if (!string.IsNullOrEmpty(printer))
                {
                    btformat.Printer = printer;
                }
                database.TextFile.FileName = filepath;

                //database.SQLStatement += $" where printID='{printId}' order by RIGHT(Var1,7)";//填写SQL语句附加条件
                //database.Password = VSLoginInfo.SQLPassword;
                //database.User = VSLoginInfo.SQLUser;
                btformat.PrintOut(false, false); //第二个参数设置是否跳出打印属性;
                btapp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);//退出时同步退出bartender进程（SQL条件会改变，不更新模板信息）

            }
            catch
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 写文本
        /// </summary>
        /// <param name="logStr"></param>
        public static string WriteLog(List<string> lines, string fileDirectory = "", string guid = "")
        {

            try
            {
                string path1 = Environment.CurrentDirectory + Path.Combine("/printFile/") + fileDirectory;
                if (!Directory.Exists(path1))
                {
                    //创建索引目录
                    Directory.CreateDirectory(path1);
                }
                string path = path1 + "/" + DateTime.Now.ToString("yyyy-MM-dd") + guid + ".txt";
                FileStream stream = null;
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                stream = new FileStream(path, FileMode.Create);

                StreamWriter writer = new StreamWriter(stream);
                for (var i = 0; i < lines.Count; i++)
                {
                    writer.Write(lines[i] + Environment.NewLine);

                }
                writer.Flush();
                writer.Close();
                stream.Close();
                return path;
            }
            catch
            {
            }
            finally
            {

            }
            return "";
        }
        #endregion

    }
}
